import router  from '../router'
import store from '../store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from './get-page-title'
import { isEmpty } from 'element-ui/src/utils/util'

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ['/login', '/404', '/update']; // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  NProgress.start();
  if (whiteList.indexOf(to.path) !== -1) {
    await store.dispatch('user/logout');
    next({ to, replace: true });
    return
  }

  // set page title
  document.title = getPageTitle(to.meta.title);
  // determine whether the user has logged in
  const hasToken = store.getters.token;

  if (hasToken) {
    let roles = store.getters.roles;
    if (isEmpty(roles) || roles.length === 0) {
      store.dispatch('user/getUserInfo').then(() => { // 拉取info
        console.info(store.getters.roles);
        roles = store.getters.roles;
        store.dispatch('permission/generateRoutes', { roles }).then(() => { // 生成可访问的路由表
          router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
          router.options.routes = store.getters.addRouters;
          let toUrl = to.path;
          if (roles.indexOf('Manager')  !== -1 || roles.indexOf('SupperManager') !== -1 ) {
            toUrl = '/user/index'
          } else {
            toUrl = '/lab/normal'
          }
          next(`${toUrl}`) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
        })
      }).catch(err => {
        console.log(err);
      })
    } else {
      next()
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
});
